package cn.enilu.flash.service.blindbox;

import cn.enilu.flash.bean.entity.blindbox.UserFunds;
import cn.enilu.flash.bean.entity.blindbox.UserFundsRecord;
import cn.enilu.flash.bean.entity.shop.Order;
import cn.enilu.flash.bean.enumeration.FlagEnum;
import cn.enilu.flash.bean.enumeration.TypeEnum;
import cn.enilu.flash.dao.blindbox.UserFundsRecordRepository;
import cn.enilu.flash.dao.blindbox.UserFundsRepository;
import cn.enilu.flash.service.BaseService;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author HYF
 * @ClassName BlindboxService
 * @date 2022年04月27日 5:08 下午
 */
@Slf4j
@Service
public class UserFundsService extends BaseService<UserFunds, Long, UserFundsRepository> {

    @Resource
    private UserFundsRepository userFundsRepository;
    @Resource
    private UserFundsRecordRepository userFundsRecordRepository;

    /**
     * 余额支付
     * @param idUser
     * @param order
     */

    @Transactional(rollbackFor = Exception.class)
    public synchronized void balancePayment(Long idUser, Order order) {
        UserFunds userFunds = userFundsRepository.findUserFundsByUserId(idUser);
        if (ObjectUtil.isEmpty(userFunds)){
            userFunds = new UserFunds();
            userFunds.setUserId(idUser);
            userFunds.setBalance(0L);
            userFunds.setIntegral(0L);
            userFunds.setAvailableFlag(true);
            insert(userFunds);
        }
        if (userFunds.getBalance()<=order.getRealPrice().longValue()){
            log.warn("id={}余额不足,{}",idUser,userFunds.getBalance());
            throw new RuntimeException("余额不足");
        }
        userFunds.setBalance(userFunds.getBalance()-order.getRealPrice().longValue());
        update(userFunds);

        UserFundsRecord userFundsRecord = new UserFundsRecord();
        userFundsRecord.setUserId(idUser);
        userFundsRecord.setFundsId(userFunds.getId());
        userFundsRecord.setQuantity(order.getTimes().longValue());
        userFundsRecord.setAvailableFlag(FlagEnum.YES.getKey());
        userFundsRecord.setRecordType(TypeEnum.RecordType.BLIND_BOX.getKey());
        userFundsRecordRepository.save(userFundsRecord);


    }

    public UserFunds findUserFundsByUserId(Long idUser) {
        return userFundsRepository.findUserFundsByUserId(idUser);
    }
}